#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/5/27 上午10:13
# @Author  : Huang-Bo
from typing import List, Dict, Optional
from utils.alicloud.base_client import AliCloudBaseClient
from alibabacloud_ecs20140526.client import Client as Ecs20140526Client
from alibabacloud_ecs20140526 import models as ecs_20140526_models
from utils.logger import setup_logger
from utils.config_loader import load_config

# 初始化配置
config = load_config()
# 设置错误日志记录器
error_logger = setup_logger("error", config["log"]["error_log"], level="ERROR")


class AliCloudEcsClient(AliCloudBaseClient):
    """
    阿里云ECS客户端类，用于获取ECS实例信息
    """
    def __init__(self, region_id: str = 'cn-hangzhou', endpoint: Optional[str] = None):
        """
        初始化AliCloudEcsClient类
        :param region_id: 地域ID，默认为'cn-hangzhou'
        :param endpoint: 接入点，默认为None，如果指定则使用指定值
        """
        super().__init__(client_class=Ecs20140526Client, region_id=region_id,
                         endpoint=endpoint or f'ecs.{region_id}.aliyuncs.com')
        self.client = self.create_client()

    def get_instances(self) -> List[Dict]:
        """
        获取ECS实例信息（包含分页逻辑）
        :return: 过滤后的实例信息，实例名称、IP、ID、状态等
        """
        instances = []
        page_number = 1
        page_size = 100
        try:
            while True:
                # 构造请求获取实例信息
                request = ecs_20140526_models.DescribeInstancesRequest(
                    region_id=self.region_id,
                    page_number=page_number,
                    page_size=page_size,
                )
                response = self.client.describe_instances(request)
                if not hasattr(response.body.instances, 'instance'):
                    break  # 没有数据跳出循环
                # 遍历实例提取相关信息
                for ins in response.body.instances.instance:
                    ip_address = ''
                    if hasattr(ins, 'vpc_attributes') and ins.vpc_attributes.private_ip_address.ip_address:
                        ip_address = ins.vpc_attributes.private_ip_address.ip_address[0]
                    elif hasattr(ins, 'public_ip_address') and ins.public_ip_address.ip_address:
                        ip_address = ins.public_ip_address.ip_address[0]
                    instances.append({
                        'instance_id': ins.instance_id,
                        'instance_name': ins.instance_name or f'未命名实例-{ins.instance_id[-8:]}',
                        'status': ins.status,
                        'os_type': ins.ostype,
                        'os_name': ins.osname,
                        'ip_address': ip_address,

                    })
                # 判断是否还有下一页
                total_count = response.body.total_count
                if page_number * page_size >= total_count:
                    break  # 已获取所有数据
                page_number += 1
        except Exception as e:
            error_logger.error(f"获取实例信息失败: {e}")
            return []
        return instances
